<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" width="60%">
    <el-row>
      <el-col :span="15">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
          label-width="100px">
          <el-row>
            <el-col :span="20">
              <el-form-item label="组件类型" prop="typeId">
                <el-select v-model="dataForm.typeId" filterable placeholder="请选择组件类型" size="medium"
                  @change="onSelectTypeify">
                  <el-option v-for="item in widgetTypeList" :key="item.id" :label="item.name"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="组件名称" prop="widgeId">
                <el-select v-model="dataForm.widgeId" filterable placeholder="请选择组件" size="medium"
                  @change="onSelectWidge">
                  <el-option v-for="item in widgeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="组件类型" prop="type">
                <el-input v-model="dataForm.type" placeholder="组件类型：如HH-mm"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="组件字体" prop="fontSize">
                <el-select v-model="dataForm.fontName" filterable placeholder="请选择组件字体">
                  <el-option v-for="item in fontOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="字体大小" prop="fontSize">
                <el-input v-model="dataForm.fontSize" placeholder="字体大小:如14"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="组件颜色：" prop="color">
                <el-input v-model="dataForm.color" placeholder="颜色值：如FFFFFF"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="X轴位置" prop="xscale">
                <el-input v-model="dataForm.xscale" placeholder="X轴布局位置"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="Y轴位置" prop="yscale">
                <el-input v-model="dataForm.yscale" placeholder="Y轴布局位置"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
      <el-col :span="9">
        <div style="position: relative;">
          <div class="bg-phone">
            <div class="bg-phone-content">
              <img :src="previewimage" style="width:100%;height:auto">
              <div>
                <div id="previewdiv1"
                  :style="'color:#' + dataForm.color + ';font-size:' + (parseInt(dataForm.fontSize) - 5) + 'px;font-family: ' + dataForm.fontName + ';position: absolute;'">
                  {{ dataTime }}</div>
                <div v-for="(item, index) in labelsValues" :id="item.id" :style="item.styles" :key="index">{{ item.value }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { parseTime } from '@/utils'
export default {
  data () {
    return {
      visible: false,
      isSelected: false,
      dataForm: {
        id: 0,
        widgeId: '',
        widgeName: '',
        typeId: '',
        typeName: '',
        type: '',
        fontSize: '',
        fontName: '',
        color: '',
        xscale: '',
        yscale: '',
      },
      dataRule: {
        widgeId: [
          { required: true, message: '组件id不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '配置类型：如yyyy-MM-dd不能为空', trigger: 'blur' }
        ],
        fontSize: [
          { required: true, message: '字体大小不能为空', trigger: 'blur' }
        ],
        fontName: [
          { required: true, message: '字体不能为空', trigger: 'blur' }
        ],
        color: [
          { required: true, message: '颜色值：如FFFFFF不能为空', trigger: 'blur' }
        ],
        xscale: [
          { required: true, message: 'X周布位置不能为空', trigger: 'blur' }
        ],
        yscale: [
          { required: true, message: 'Y周布位置不能为空', trigger: 'blur' }
        ],
      },
      widge: {},
      widgeList: [],
      widgetTypeList: [],
      fontOptions: [{
        value: 'TsangerFeiBai',
        label: 'TsangerFeiBai'
      }, {
        value: '仓耳小丸子',
        label: '仓耳小丸子'
      }, {
        value: 'muyao',
        label: 'muyao'
      }, {
        value: 'YouSheBiaoTiHei',
        label: 'YouSheBiaoTiHei'
      }, {
        value: 'HappyZcool-2016',
        label: 'HappyZcool-2016'
      }, {
        value: 'baotuxiaobaiti',
        label: 'baotuxiaobaiti'
      }, {
        value: 'DOUYU',
        label: 'DOUYU'
      }, {
        value: 'PangMenZhengDao',
        label: 'PangMenZhengDao'
      }, {
        value: 'QTxiaotu',
        label: 'QTxiaotu'
      }, {
        value: 'Dancing Script',
        label: 'Dancing Script'
      }, {
        value: 'MuYaoSoftbrush',
        label: 'MuYaoSoftbrush'
      }, {
        value: 'MiSans-Thin',
        label: 'MiSans-Thin'
      }, {
        value: 'MiSans-Regular',
        label: 'MiSans-Regular'
      }, {
        value: 'MiSans-Medium',
        label: 'MiSans-Medium'
      }, {
        value: 'MiSans-Heavy',
        label: 'MiSans-Heavy'
      }, {
        value: 'MiSans-Bold',
        label: 'MiSans-Bold'
      }],
      previewimage: '',
      dataTime: '',
      labels: [],
      labelsValues: []
    }
  },
  watch: {
    'dataForm.type': {
      handler: function (val, oldVal) {
        if (this.dataForm.type == 'weekday') {
          this.dataTime = '星期' + parseTime(new Date(), '{a}')
        } else if (this.dataForm.type == 'yyyy.MM.dd ' || this.dataForm.type == 'yyyy.MM.dd') {
          this.dataTime = parseTime(new Date(), '{y}.{m}.{d}')
        } else if (this.dataForm.type == 'HH:mm') {
          this.dataTime = parseTime(new Date(), '{h}:{i}')
        } else {
          this.dataTime = parseTime(new Date(), '{h}:{i}')
        }
      },
      deep: true
    },
    'dataForm.xscale': {
      handler: function (val, oldVal) {
        let img_url = this.previewimage
        let xscale = this.dataForm.xscale
        // 创建对象
        var img = new Image()
        let imgheight = 0
        // 改变图片的src
        img.src = img_url
        // 加载完成执行
        img.onload = function () {
          // let that = this
          //   // 获取宽度比例求div中的高度
          // let scale = 300 /img.width
          // imgheight = scale * img.height
          // that.imgheight = imgheight
          imgheight = 150
          // alert(this.imgheight)
          let previewdiv1 = document.getElementById('previewdiv1')
          previewdiv1.style.left = 300 * xscale + 'px'
        }
      },
      deep: true
    },
    'dataForm.yscale': {
      handler: function (val, oldVal) {
        let img_url = this.previewimage
        let yscale = this.dataForm.yscale
        let fontSize = this.dataForm.fontSize
        // 创建对象
        var img = new Image()
        let imgheight = 0
        // 改变图片的src
        img.src = img_url
        // 加载完成执行
        img.onload = function () {
          let that = this
          // 获取宽度比例求div中的高度
          // let scale = 300 /img.width
          // imgheight = scale * img.height
          // that.imgheight = imgheight
          imgheight = 150
          // alert(this.imgheight)
          let previewdiv1 = document.getElementById('previewdiv1')
          // left: '+ 240 * dataForm.xscale +'px;top: '+ imgheight *  dataForm.yscale +'px;
          previewdiv1.style.top = imgheight * yscale + (parseInt(fontSize) - 25) + 'px'
        }
      },
      deep: true
    },
  },
  methods: {
    init (widge) {
      this.visible = true
      this.isSelected = false
      this.initWidgeList()
      this.initWidgeTypeList()
      if (widge != null && widge != '') {
        this.isSelected = true
        this.dataForm.widgeId = widge.id
        this.dataForm.typeId = widge.typeId
        this.dataForm.typeName = widge.typeName
        this.previewimage = widge.image

        this.$nextTick(() => {
          let previewdiv1 = document.getElementById('previewdiv1')
          previewdiv1.style.top = '0px'
          previewdiv1.style.left = '0px'
        })

        // 在此获取labels的值
        this.labels = widge.widgeLayoutList
        var img_url = this.previewimage
        // 创建对象
        var img = new Image()
        let imgheight = 0
        // 改变图片的src
        img.src = img_url
        img.onload = function () {
          // 获取宽度比例求div中的高度
          // let scale = 300 /img.width
          // imgheight = scale * img.height
          imgheight = 150
          getStylesVal(imgheight)
        }

        let that = this
        function getStylesVal (imgheight) {
          that.labelsValues = []
          that.labels.forEach(item => {
            const l = {}
            l.id = item.id
            if (item.type == 'weekday') {
              l.value = '星期' + parseTime(new Date(), '{a}')
            } else if (item.type == 'yyyy.MM.dd ' || item.type == 'yyyy.MM.dd') {
              l.value = parseTime(new Date(), '{y}.{m}.{d}')
            } else if (item.type == 'HH:mm') {
              l.value = parseTime(new Date(), '{h}:{i}')
            } else {
              l.value = parseTime(new Date(), '{h}:{i}')
            }
            if (parseInt(item.fontSize) > 45) {
              item.fontSize = item.fontSize - 5
            }
            l.styles =
              'color: #' + item.color + ';font-size:' +
              parseInt(item.fontSize) + 'px;font-family: ' +
              item.fontName + ';position: absolute;left:' +
              300 * item.xscale + 'px;top:' + (imgheight * item.yscale + (parseInt(item.fontSize) - 25)) + 'px;'
            that.labelsValues.push(l)
          })
        }
      }
    },
    initWidgeTypeList () {
      this.$http({
        url: this.$http.adornUrl('/widge/widge-type/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.widgetTypeList = data.page.list
        }
      })
    },
    // 筛选类型
    onSelectTypeify (val) {
      let obj = this.widgetTypeList.find((item) => {
        return item.id === val;
      });
      this.dataForm.typeName = obj.name
      this.initWidgeList()
    },
    initWidgeList () {
      this.themeWidgeList = []
      this.$http({
        url: this.$http.adornUrl('/widge/widge/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          'typeId': this.dataForm.typeId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.widgeList = data.page.list
        }
      })
    },
    // 筛选类型
    onSelectWidge (val) {
      this.widgeList.forEach((item, index) => {
        if (item.id === val) {
          this.widge = item
          this.previewimage = item.image
        }
      })
      this.dataForm.widgeId = this.widge.id
      this.dataForm.widgeName = this.widge.name
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/widge/widge-layout/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'widgeId': this.dataForm.widgeId,
              'type': this.dataForm.type,
              'fontSize': this.dataForm.fontSize,
              'fontName': this.dataForm.fontName,
              'color': this.dataForm.color,
              'xscale': this.dataForm.xscale,
              'yscale': this.dataForm.yscale,
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.bg-phone {
  /* background: url('../../../assets/img/phone.png') no-repeat;
  background-size: 100%; */
  width: 360px;
  height: 610px;
  padding: 50px 30px 30px 30px;
  margin: 0 auto;
}

.bg-phone-content {
  /* background: #fff; */
  height: 560px;
  border-radius: 5px;
  position: relative;
}
</style>
